package com.swg.seckill.rabbitmq;


import com.swg.seckill.pojo.SeckillOrder;
import com.swg.seckill.pojo.User;
import com.swg.seckill.pojo.seckillMessage;
import com.swg.seckill.service.IGoodsService;
import com.swg.seckill.service.impl.OrderServiceImpl;
import com.swg.seckill.utils.JacksonUtil;
import com.swg.seckill.utils.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReciver {
    @Autowired
    private IGoodsService iGoodsService;

    @Autowired
    @Qualifier("myRedisTemplate")
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderServiceImpl orderService;

    /**
     * 下订单操作
     */
    @RabbitListener(queues = "seckillQueue")
    public void recive(String message){
        seckillMessage seckillMessage1 = new seckillMessage();
        log.info("接收到的消息为: " + message);
        String s = JacksonUtil.toJson(message);
        seckillMessage seckillMessage = JacksonUtil.fromJson(message, seckillMessage1.getClass());
        Long goodsId = seckillMessage.getGoodsId();
        User user = seckillMessage.getUser();

        GoodsVo goodsVo = iGoodsService.listGoods(goodsId);
        if(goodsVo.getStockCount() < 1){
            return;
        }
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if(seckillOrder != null){
            return ;
        }
        orderService.sekill(user, goodsVo);
    }


}
